import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../../services/http.service';
import { LoginInfoService } from '../../../services/login-info.service';
import { AlertController } from '@ionic/angular';
import { Router } from '@angular/router';
import { BaseUiService } from '../../../services/base-ui.service';
import { WebsocketService } from '../../../services/websocket.service';

@Component({
  selector: 'app-sanfanshipin',
  templateUrl: './sanfanshipin.page.html',
  styleUrls: ['./sanfanshipin.page.scss'],
})
export class SanfanshipinPage implements OnInit {
  public userIdcard:any //当前登录人的身份证
  public inviteeName:string //被邀请人姓名
  public inviteeMobile:string //被邀请人手机号
  public inviteeIdcard:string //被邀请人身份证
  constructor(
    public router: Router,
    public baseUiService: BaseUiService,
    public HttpService: HttpService,
    public wsCoket: WebsocketService,
    public LoginInfoService: LoginInfoService,
    public alertController: AlertController
  ) { }

  ngOnInit() {
    this.userIdcard = this.LoginInfoService.getlocal("user").idCard
    this.entrance()
  }
  //一进入就查询
  entrance(){
    let p = {
      idCard: this.userIdcard
    }
    this.HttpService.Que_contract(p).then(res =>{
      if(res['item'].state == 200){
        
        this.presentAlert(res['item'].notaryOrder)
      }
    })
  }
  //弹出是否有一个待办的合同
  async presentAlert(info:any) {
    const alert = await this.alertController.create({
      header: '公证合同提醒',
      subHeader: '',
      message: '你有个合同公证正在等待你的加入，请操作',
      buttons: [
        {
          text: '取消',
          handler: () => {
            this.router.navigate(['/tabs/tab2']);
          }
        },
        {
          text: '确定',
          handler: () => {
            this.LoginInfoService.setlocal('orderInfo', info)
            this.router.navigate(['/transaction/sanfanvideo']);
            let urlId = this.HttpService.websockurl() + this.LoginInfoService.getInfo().idCard
            this.wsCoket.createObservableScoket(urlId);
          }
        }
      ]
    });

    await alert.present();
  }
  getDate(){
      var myDate = new Date();
      //获取当前年
      var year = myDate.getFullYear();
      //获取当前月
      var month = myDate.getMonth() + 1;
      //获取当前日
      var date = myDate.getDate();
      //var now = year + '-' + this.conver(month) + "-" + this.conver(date) + " " + this.conver(h) + ':' + this.conver(m) + ":" + this.conver(s);
      var now = year + '-' + this.conver(month) + "-" + this.conver(date)
      return now;
  }
  //日期时间处理
  conver(s) {
    return s < 10 ? '0' + s : s;
  }
  //点击去合同公证
  gosfvideo(){
    // return this.router.navigate(['/transaction/sanfanvideo']);
    let that = this;
    let p = {
      userId: this.LoginInfoService.getInfo().unitGuid,
      name:this.LoginInfoService.getInfo().userName,
      useArea:"",
      useLanguage:"",
      purposeName:"",
      notaryId:'666c2421-b2e1-4076-80aa-8e63cf287de4',
      isDaiBan:0,
      terminalType: 1,
      notaryForm:3,
      description:"",
      videolog:JSON.stringify({
        planDate:this.getDate()
      }),
      applyUsers:JSON.stringify([{
        name: this.LoginInfoService.getInfo().userName,
        gender: this.LoginInfoService.getInfo().gender,
        birthday: this.LoginInfoService.getInfo().birthday,
        idCard: this.LoginInfoService.getInfo().idCard,
        mobile: this.LoginInfoService.getInfo().mobile
      }]),
      thirdPartyIdCard: this.inviteeIdcard,
      thirdPartyMob:this.inviteeMobile,
      thirdPartyName: this.inviteeName
      
    }
    this.HttpService.machineAdd(p).then(res =>{
      console.log(res,'-+-+-')
      if(res['code'] == 200){
        let urlId = this.HttpService.websockurl() + this.LoginInfoService.getInfo().idCard
        this.wsCoket.createObservableScoket(urlId);
        if(res['unitGuid'].code == 11022){
          this.baseUiService.showLoading('正在等待公证员',0);
          //等待六十秒
          let timeOut = setTimeout(()=>{
            that.HttpService.shutVideoOrder({unitGuid: res['unitGuid'].unitGuid})
            that.baseUiService.hideLoading();
            that.wsCoket.closeWebSocket();
            that.baseUiService.showLoading('公证员正在忙碌，请稍后重试',1000);
          },60000)
          this.wsCoket.getMessage().subscribe(data => {
            if(data.code == 'dontWiting'){
              clearTimeout(timeOut)
              console.log(data,'-+-+-')
              that.baseUiService.hideLoading();
              let info = {
                orderNo: data.orderNo,
                roomId: data.roomId
              }
              console.log(info,'-+-+-')
              setTimeout(()=>{
                that.LoginInfoService.setlocal('orderInfo', info)
                that.router.navigate(['/transaction/sanfanvideo']);
              },1000)
              
            }
          })
        }else{
          this.LoginInfoService.setlocal('orderInfo', res['unitGuid'])
          this.router.navigate(['/transaction/sanfanvideo']);
        }
      }
    })
  }
}
